var $table;  
var selectionIds = [];  //保存选中ids  
var sysLogField = dataObject.sysLogField;
var logData = dataObject.logData;
var sysLog = dataObject.syslog;
var sysLogModule = dataObject.sysLogModule;
var advScheduleField = dataObject.advScheduleField;
var executeTime = null;
var allotParam = "";
$(function () {
	  var columns =[
					{field: 'state', checkbox: true},
					{field: 'username' , title: sysLogField.username, sortName:'USER_NAME' , sortable: true,halign: 'center',align: 'center'},
					{field: 'type' , title: sysLogField.type,formatter: 'logTypeFormatter', sortName:'TYPE' , sortable: true,halign: 'center',align: 'center'},
//					{field: 'operation' , title: sysLogField.operation,formatter: 'logOperatFormatter', sortName:'operation' , sortable: true,halign: 'center',align: 'center'},
					/*{field: 'method' , title: sysLogField.method, sortName:'method' , sortable: true,halign: 'center',align: 'center'},*/
					/*{field: 'params' , title: sysLogField.params, sortName:'params' , sortable: true,halign: 'center',align: 'center'},*/
					{field: 'ip' , title: sysLogField.ip, sortName:'ip' , sortable: true,halign: 'center',align: 'center'},
					{field: 'createDate' , title: sysLogField.createDate, sortName:'CREATE_DATE' , sortable: true,halign: 'center',align: 'center'},
					{field: 'operation' , title: sysLogField.operation,formatter: 'logOperatFormatter', sortName:'operation' , events: 'allotEvent', sortable: true,halign: 'center',align: 'center'},
					{field: 'action', title: pageData.detail, formatter: 'actionFormatter', events: 'actionEvent', clickToSelect: false, width: 150, halign: 'center', align: 'center'}
		         ];
    $table = new BSTable("table", 'sys/syslog/list', columns,"toolbar",520,'id','id','syslog');
    var queryParams = function(params) {            
         return {
         	  page: params.pageNumber,
         	  limit: params.pageSize,
         	  sidx: params.sortName,
              order: params.sortOrder,
              username: vm.search.username,
              type: vm.search.type,
              beginTime:vm.search.searchBeginTime,
              endTime:vm.search.searchEndTime
              //查询字段
            };
    };
	$table.setQueryParams(queryParams);
    $table.init();
    
    $.ajax({
        type: 'get',
        async: false,
        url: $path+'/sys/syslog/loadLogDocument',
        success: function (r) {
           var arr = r.files;
           if(arr){
        	   for (var i = 0; i < arr.length; i++) {
        		  $("#downloadLog").append("<option value='"+arr[i]+"'>"+arr[i]+"</option>");
			}
           }
        }
   });
    
    /*var executeTime = laydate.render({
		   elem: '#executeTime',
		   type: 'time',
		   //min: new Date().getTime(),
		   //max: '2099-06-16 23:59:59',
		   btns: ['clear','now','confirm'],
		   lang: lang,
		   done: function(value, date){
			   if(value != ''){
				   date.month = date.month - 1;
				   //Vue.set(vm.busContract,'signingTime',value);
			   	   $('#signingTime').val(value).change();
			   }
		   }
	});*/
    
    var searchBeginTime = laydate.render({
 	   elem: '#searchBeginTime',
       type: 'datetime',
       min: '1900-01-01 00:00:00',
       max: '2099-06-16 23:59:59',
 	   lang: lang,
 	   btns: ['clear', 'confirm'],
 	   done:function(value , date){
 		  vm.search.searchBeginTime='';
 		   if (value != '') {
 			   date.month = date.month - 1;
 			  searchEndTime.config.min = date;
 			  vm.search.searchBeginTime = value;
 		}else {
 			 date.month = date.month - 1;
			searchEndTime.config.min = searchBeginTime.config.min;
 			 vm.search.beginTime = value;
 		}
 	   }
 });
    
 var searchEndTime = laydate.render({
 	   elem: '#searchEndTime',
       type: 'datetime',
       min: '1900-01-01 00:00:00',
       max: '2099-06-16 23:59:59',
 	   lang: lang,
 	   btns: ['clear', 'confirm'],
 	   done:function(value , date){
 		  vm.search.searchEndTime='';
 		   if (value != '') {
 			   date.month = date.month - 1;
 			  searchBeginTime.config.max = date;
 			   vm.search.searchEndTime = value;
 		}else {
 			date.month = date.month - 1;
 			searchBeginTime.config.max =  searchEndTime.config.max;
 			  vm.search.endTime = value;
 		}
 	   }
 });
});

//状态码显示格式
function logTypeFormatter(value,row){
	return value == 1 ? "<span class='label label-warning'>"+logData[value]+"</span>" :
		   value == 3? "<span class='label label-info'>"+logData[value]+"</span>" :
		   "<span class='label label-success'>"+logData["2"]+"</span>";
}

function logOperatFormatter(value,row){
	debugger;
	var showOperate = null;
	if(undefined != row.className && null != row.className && undefined != sysLogModule[row.className]){
		showOperate = sysLogModule[row.className] + " -> " + sysLog[value];
		if(undefined != row.result && null != row.result && !isNaN(row.result) && "addAllot" != row.operation && "delAllot" != row.operation)
			showOperate += " -> " + statusFormatter(row.result, row.className);
		if("addAllot" == row.operation || "delAllot" == row.operation) {
			var button = [];
			button.push('<a class="allot ml10" href="javascript:void(0)"  data-toggle="tooltip" title="allot value">'+pageData.allotDetail+'</a>&nbsp;&nbsp;');
			showOperate += " -> " + button.join('');	
			//"<a class=\"allot ml10\" class=\"btn btn-primary\" v-on:click=\"allot\">"+pageData.detail+"</a>";
		}
	}else{
		showOperate = sysLog[value]
	}
	return showOperate;
}
//状态行数据格式化
function statusFormatter(value,controllerName){
	if(controllerName!="AdvScheduleController") {
		return  value == 0 ? pageData.auditNoSubmit:
		    value == 1? pageData.auditSubmit:
		    value == 2 ? pageData.auditPass:
		    value == 8 ? pageData.startUsed: 
		    value == 9 ? pageData.stopUsed: 
		    value == 10 ? pageData.lock: 
		    value == 11 ? pageData.freeze: 
		    value == 4 ?   pageData.inject: 
		    value == 5 ?   pageData.uninject: 
		    value == 12 ?   pageData.injecting: 
			value == 13 ?   pageData.uninjecting: 
			value == 14 ?   pageData.injectFailed: 
			value == 15 ?   pageData.uninjectFailed: 
			value == 7 ? pageData.auditRevoked: 
			pageData.auditNoPass;
	}
	if(controllerName=="AdvScheduleController") {
		var expression = {
				0:pageData.auditNoSubmit,
				1:pageData.auditSubmit,
				2:pageData.auditPass ,
				3:pageData.auditNoPass ,
				4:pageData.play,
				5:pageData.unplay ,
				6:pageData.pause ,
				7:advScheduleField.invalid,
				"-1":advScheduleField.invalid
			};
		return expression[value];
	}
}
window.actionEvent = {    
	    'click .new': function (e, value, row, index) {
	    	window.parent.Tab.addTab(sysLogModule[row.className]+"[LOG-NEW]",row.url+"?id="+row.id+"&type=1&logDetailPage");
	    },
	    'click .old': function (e, value, row, index) {
	    	window.parent.Tab.addTab(sysLogModule[row.className]+"[LOG-OLD]",row.url+"?id="+row.id+"&type=2&logDetailPage");
	    }
};
window.allotEvent = {    
	    'click .allot': function (e, value, row, index) {
	    	vm.allot(e, row.params, value);
	    }
};

var actionFormatter = function(value, row, index) {
	var button = [];
	if(row.operateValue != null){
		button.push('<a class="new ml10" href="javascript:void(0)" data-toggle="tooltip" title="new value">'+pageData.detail+'</a>&nbsp;&nbsp;');
	}
	if(row.updateOld != null){
		button.push('<a class="old ml10" href="javascript:void(0)"  data-toggle="tooltip" title="old value">'+sysLogField.detailOld+'</a>&nbsp;&nbsp;');	
	}
	return button.join('');
};

/*function loadBackupLog(){
	//$("#downloadLog").onclick(function(){
	//	alert("加载历史日志文件！");
	//});
	//$("#downloadLog").empty();
	//$("#downloadLog").append("<option value=''>请选择</option>");
		$.ajax({
            type: 'get',
            async: false,
            url: '../sys/syslog/loadLogDocument',
            success: function (r) {
               var arr = r.files;
               if(arr){
            	   for (var i = 0; i < arr.length; i++) {
            		  $("#downloadLog").append("<option value='"+arr[i]+"'>"+arr[i]+"</option>");
				}
               }
            }
       })
}*/


var vm = new Vue({
	el:'#app',
	data:{
		showList: true,
		showSetBackupDetail: false,
		title: null,
		sysLog: {			
		},
		sysLogConfig: {
			logBackupType:'',
			logRunType:'',
		},
		search:{
			id:null,
			type:""
		}
	},
	methods: {
		query: function () {
			defaultActions.query();
		},
		add: function(){
		    vm.sysLog={};
			defaultActions.add(vm);
		},
		update: function (event, id) {
		    defaultActions.update(id, $("#table"),$path+"/sys/syslog/info/", vm, function(r){
	        	vm["sysLog"] = r["sysLog"];
	        });
		},
		saveOrUpdate: function (event) {
		    $('#defaultForm').bootstrapValidator('validate');
			if($('#defaultForm').data('bootstrapValidator').isValid()){
				 var url = vm.sysLog.id == null || vm.sysLog.id == ''? ($path+"/sys/syslog/save") : ($path+"/sys/syslog/update");
				 defaultActions.saveOrUpdate(url ,vm, $("#defaultForm"),"sysLog",event);
			}
		},
		saveOrUpdateSysLogConfig: function (event) {
			$('#defaultForm').bootstrapValidator('validate');
			if($('#defaultForm').data('bootstrapValidator').isValid()){
				if(!vm.sysLogConfig.logBackupType){
					alert(pageData.noteEmptyBackupTime);
					return;
				}
				if(!vm.sysLogConfig.logRunType){
					alert(pageData.noteEmptyExecuteType);
					return;
				}
				var logBackupPath = $('#logBackupPath').val();
				var reg1=/^[a-zA-Z]:[\\/]((?! )(?![^\\/]*\s+[\\/])[\w -]+[\\/])*(?! )(?![^.]+\s+\.)[\w -]+$/;
                var reg2=/^([\/][\w-]+)*$/;
				if(!logBackupPath){
					alert(pageData.noteEmptyLogBackupPath);
					return;
				}else{
					if(reg1.test(logBackupPath) || reg2.test(logBackupPath)){
						vm.sysLogConfig.logBackupPath = logBackupPath;
					}else {
						alert('备份地址格式错误');
						return;
					}
				}
				var logRunTimestr = $('#executeTime').val();
				if(!logRunTimestr){
					alert(pageData.noteEmptyExecuteTime);
					return;
				}else{
					vm.sysLogConfig.logRunTimestr = logRunTimestr;
				}
				var url = vm.sysLogConfig.logConfigNo == null || vm.sysLogConfig.logConfigNo == ''? ($path+"/sys/syslog/saveSysLogConfig") : ($path+"/sys/syslog/updateSysLogConfig");
				defaultActions.saveOrUpdate(url ,vm, $("#defaultForm"),"sysLogConfig",event);
			}
		},
		del: function (event, id) {
		    defaultActions.del(id, $path+"/sys/syslog/delete", $("#table") ) ;
		},
		audit:function(status){
			defaultActions.audit(status , $path+"/sys/syslog/audit?status="+status, vm);
		},
		reload: function (event) {
		    defaultActions.reload($("#table"),$("#defaultForm"),vm,"sysLogConfig"); 
		    vm.showSetBackupDetail = false;
		},
		setBackupDetail: function(){
			/*vm.sysLogConfig={
					logBackupType:'',
					logRunType:'',
		    };*/
			$.ajax({
                 type: 'get',
                 async: false,
                 url: $path+'/sys/syslog/sysLogConfigInfo/1',
                 success: function (r) {
                	if(r.sysLogConfig){
                		vm.sysLogConfig = r.sysLogConfig;
                	}
                 }
            });
			vm.showList = false;
			vm.showSetBackupDetail = true;
			vm.title = pageData.setBackupDetail;
			if(vm.sysLogConfig){
				$('#executeTime').val(vm.sysLogConfig.logRunTimestr).change();
				$('#logBackupPath').val(vm.sysLogConfig.logBackupPath).change();
			}
			executeTime = laydate.render({
				   elem: '#executeTime',
				   type: 'time',
				   //min: new Date().getTime(),
				   //max: '2099-06-16 23:59:59',
				   btns: ['clear','now','confirm'],
				   lang: lang,
				   done: function(value, date){
					   if(value != ''){
						   date.month = date.month - 1;
						   //Vue.set(vm.sysLogConfig,'logRunTimestr',value);
					   	   $('#executeTime').val(value).change();
					   }
				   }
			});
		},
		backupLog: function(){
			var beginTime = vm.search.searchBeginTime;
			var endTime = vm.search.searchEndTime;
			if(!beginTime || !endTime){
				alert(pageData.selectOperationTimeTip);
				return;
			}
			
			if(beginTime >= endTime){
				alert("开始时间不能大于等于结束时间！");
				return;
			}
			confirm(pageData.sureBackupTip,function(){
				$.ajax({
					type: 'get',
					async: false,
					url: $path+'/sys/syslog/sysLogConfigInfo/mtBackup/' + beginTime + "/" + endTime,
					success: function (r) {
						alert(r.msg);
					}
				})
			});
		},
		downloadLog: function(){
			var downloadLog = $('#downloadLog').val();
			if(!downloadLog){
				alert(pageData.selectFileTip);
				return;
			}
			/*$.ajax({
				type: 'get',
				async: false,
				url: '../sys/syslog/downloadLogDocument/' + downloadLog,
				success: function (r) {
					//alert(r.msg);
				}
			})*/
			window.location.href = $path+'/sys/syslog/downloadLogDocument/' + downloadLog;
		}
		
	}
});

/*表单校验 start*/
$('#defaultForm').bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
	    			    				
	    	/*username: {
	            message: 'The 用户名 is not valid',
	            validators: {
	                notEmpty: {
	                    message: sysLogField.username+'不能为空！'
	                }
	            }
	        },
	    	    				
	    	operation: {
	            message: 'The 用户操作 is not valid',
	            validators: {
	                notEmpty: {
	                    message: sysLogField.operation+'不能为空！'
	                }
	            }
	        },
	    	    				
	    	method: {
	            message: 'The 请求方法 is not valid',
	            validators: {
	                notEmpty: {
	                    message: sysLogField.method+'不能为空！'
	                }
	            }
	        },
	    	    				
	    	params: {
	            message: 'The 请求参数 is not valid',
	            validators: {
	                notEmpty: {
	                    message: sysLogField.params+'不能为空！'
	                }
	            }
	        },
	    	    				
	    	ip: {
	            message: 'The IP地址 is not valid',
	            validators: {
	                notEmpty: {
	                    message: sysLogField.ip+'不能为空！'
	                }
	            }
	        },
	    	    				
	    	createDate: {
	            message: 'The 创建时间 is not valid',
	            validators: {
	                notEmpty: {
	                    message: sysLogField.createDate+'不能为空！'
	                }
	            }
	        },*/
    		/*logBackupPath: {
	            message: 'The 备份目录地址 is not valid',
	            validators: {
	                notEmpty: {
	                    message: sysLogField.logBackupPath+'不能为空！'
	                },
	                regexp:{
	                	regexp:/^[\w].*$/,
	                	message:pageData.backupPathFormat
	                }
	            }
	        }*/
	    	    		    
    }
});
/*表单校验 end*/
